#!/usr/bin/env python3
"""
用户管理脚本
用于创建和管理教师账号
"""

import sys

sys.path.append('src')
from user_manager import user_db

def create_teacher_account():
    """创建教师账号"""
    print("=== 创建教师账号 ===")
    
    username = input("请输入用户名: ").strip()
    if not username:
        print("用户名不能为空")
        return
    
    # 检查用户名是否已存在
    existing_users = user_db.get_all_users()
    for user in existing_users:
        if user.username == username:
            print(f"用户名 '{username}' 已存在")
            return
    
    password = input("请输入密码: ").strip()
    if not password:
        print("密码不能为空")
        return
    
    real_name = input("请输入真实姓名: ").strip()
    if not real_name:
        print("真实姓名不能为空")
        return
    
    email = input("请输入邮箱 (可选): ").strip()
    if not email:
        email = None
    
    try:
        user_id = user_db.create_user(username, password, real_name, email, "teacher")
        print(f"教师账号创建成功!")
        print(f"  用户ID: {user_id}")
        print(f"  用户名: {username}")
        print(f"  真实姓名: {real_name}")
        print(f"  邮箱: {email or '未设置'}")
        print(f"  角色: teacher")
    except Exception as e:
        print(f"创建账号失败: {e}")

def list_users():
    """列出所有用户"""
    print("=== 用户列表 ===")
    try:
        users = user_db.get_all_users()
        if not users:
            print("暂无用户")
            return
        
        print(f"{'ID':<5} {'用户名':<15} {'真实姓名':<15} {'角色':<10} {'邮箱':<25} {'最后登录':<20}")
        print("-" * 100)
        
        for user in users:
            last_login = user.last_login.strftime('%Y-%m-%d %H:%M:%S') if user.last_login else '从未登录'
            email = user.email or '未设置'
            print(f"{user.id:<5} {user.username:<15} {user.real_name:<15} {user.role:<10} {email:<25} {last_login:<20}")
            
    except Exception as e:
        print(f"获取用户列表失败: {e}")

def change_password():
    """修改密码"""
    print("=== 修改密码 ===")
    
    username = input("请输入用户名: ").strip()
    if not username:
        print("用户名不能为空")
        return
    
    # 查找用户
    users = user_db.get_all_users()
    target_user = None
    for user in users:
        if user.username == username:
            target_user = user
            break
    
    if not target_user:
        print(f"用户 '{username}' 不存在")
        return
    
    new_password = input("请输入新密码: ").strip()
    if not new_password:
        print("密码不能为空")
        return
    
    try:
        success = user_db.update_user_password(target_user.id, new_password)
        if success:
            print(f"用户 '{username}' 的密码修改成功")
        else:
            print("密码修改失败")
    except Exception as e:
        print(f"修改密码失败: {e}")

def main():
    """主菜单"""
    while True:
        print("\n" + "="*50)
        print("用户管理系统")
        print("="*50)
        print("1. 创建教师账号")
        print("2. 查看用户列表")
        print("3. 修改密码")
        print("4. 退出")
        print("-"*50)
        
        choice = input("请选择操作 (1-4): ").strip()
        
        if choice == '1':
            create_teacher_account()
        elif choice == '2':
            list_users()
        elif choice == '3':
            change_password()
        elif choice == '4':
            print("退出系统")
            break
        else:
            print("无效选择，请重新输入")

if __name__ == "__main__":
    try:
        main()
    except KeyboardInterrupt:
        print("\n\n程序被用户中断")
    except Exception as e:
        print(f"\n程序运行出错: {e}")
